package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText ip;
    private EditText port;
    private EditText send;
    private TextView tv_re;
    private Button btn_conn;
    private Button btn_send;
    private Socket socket;
    private String str_ip;
    private int port_num;
    private String temp_str;
    private String read_str;
    private Timer timer;
    private ReceiveData receiveData;
    private PrintStream printStream;
    private ConnectThread connectThread;
    private BufferedReader bufferedReader;
    private myHandler myhandler = new myHandler();

    private void  startTimer() {
        if (timer == null) {
            timer = new Timer();
        }
        if (receiveData == null) {
            receiveData = new ReceiveData();
        }
        timer.schedule(receiveData, 0, 10);
    }

    private void stopTimer() {
        if (receiveData != null) {
            receiveData.cancel();
            receiveData = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        startTimer();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTimer();
    }

    private class myHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1212:
                    tv_re.setText(read_str);
                    break;
            }
        }
    }

    private class ConnectThread extends Thread {
        private String ip_con;
        private int port_con;
        public ConnectThread(String ip_con, int port_con) {
            this.ip_con = ip_con;
            this.port_con = port_con;
        }

        @Override
        public void run() {
            try {
                socket = new Socket(ip_con, port_con);
                printStream = new PrintStream(socket.getOutputStream());
                bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btn_conn.setText("断开");
                        Toast.makeText(MainActivity.this, "Sucessful!", Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }

    private class ReceiveData extends TimerTask {
        @Override
        public void run() {
            try {
                if (bufferedReader != null && (bufferedReader.ready())) {
                    char[] readbuffer = new char[50];
                    byte[] readByte = new byte[50];
                    bufferedReader.read(readbuffer, 0, readbuffer.length);
                    temp_str = String.valueOf(readbuffer);
                    readByte = temp_str.getBytes();
                    read_str = new String(readByte, 0, readByte.length, "GB2312");
                    Message message = Message.obtain();
                    message.what = 1212;
                    myhandler.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    private void init()
    {
        ip = (EditText)findViewById(R.id.ip);
        port = (EditText)findViewById(R.id.port);
        send = (EditText)findViewById(R.id.send);
        tv_re = (TextView)findViewById(R.id.tv_re);
        btn_conn = (Button)findViewById(R.id.btn_conn);
        btn_send = (Button)findViewById(R.id.btn_send);
        btn_send.setOnClickListener(this);
        btn_conn.setOnClickListener(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_conn:
                if (socket == null || !socket.isConnected()) {
                    if (!TextUtils.isEmpty(ip.getText()) && !TextUtils.isEmpty(port.getText())) {
                        str_ip = ip.getText().toString();
                        port_num = Integer.valueOf(port.getText().toString());
                        connectThread = new ConnectThread(str_ip, port_num);
                        connectThread.start();
                    } else if (TextUtils.isEmpty(ip.getText())) {
                        Toast.makeText(MainActivity.this, "IP is null!", Toast.LENGTH_SHORT).show();
                    } else if (TextUtils.isEmpty(port.getText())) {
                        Toast.makeText(MainActivity.this, "Port is null!", Toast.LENGTH_SHORT).show();
                    }
                }
                if (socket != null && socket.isConnected()){
                    try {
                        socket.close();
                        socket = null;
                        btn_conn.setText("连接");
                        Toast.makeText(MainActivity.this, "Interrupt!", Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.btn_send:
                String str_send = send.getText().toString();
                if (str_send != null && printStream != null) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            printStream.print(str_send);
                            printStream.flush();
                        }
                    }).start();
                }
                break;
        }
    }
}